package org.kernely.core.dao;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.kernely.core.persistence.Settings;
import org.kernely.persistence.service.SessionService;
import org.osgi.service.component.ComponentContext;

/**
 * Provides methods to manipulate Settings
 */
public class SettingsDAO {
	/**
	 * SessionService service
	 */
	private static SessionService service;

	/**
	 * The DAO instance
	 */
	private static SettingsDAO instance;

	/**
	 * To give settings instance
	 * @return the settings dao
	 */
	public static SettingsDAO getInstance() {
		return instance;
	}
	
	/**
	 * Set the persistence session service
	 * @param sessionService the session service to set
	 */
	public final void setPersistenceService(SessionService sessionService) {
		service = sessionService;
	}

	/**
	 * Activate the component
	 * @param ctxt the activation context
	 */
	protected final void activate(ComponentContext ctxt) {
		instance =this;
	}


	/**
	 * Return all users registered
	 * 
	 * @return a set which contains all settings
	 */
	public final Set<Settings> getSettings() {
		Session session = service.getSession();
		Set<Settings> set = new HashSet();
		set.addAll(session.createCriteria(Settings.class).list());
		return set ;
	}

	/**
	 * Get a specific settings, by its bundle and key.
	 * @param bundle The bundle of the settings.
	 * @param key The key of the settings.
	 * @return The settings.
	 */
	public final Settings findSettings(String bundle, String key) {
		Session session = service.getSession();
		Criteria crit = session.createCriteria(Settings.class);
		crit.add(Restrictions.like("bundle", bundle));
		crit.add(Restrictions.like("key", key));
		List list = crit.list();
		if (list == null || list.size() <= 0){
			return null;
		}
		return (Settings) list.get(0);
		
	}

	/**
	 * Persist a new settings
	 * 
	 * @param settings
	 *            : the settings
	 */
	public final void save(Settings settings) {
		Session session = service.getSession();
		session.save(settings);
	}

	/**
	 * Update a settings
	 * 
	 * @param settings
	 *            : the user
	 */
	public final void update(Settings settings) {
		Session session = service.getSession();
		session.merge(settings);
	}


	/**
	 * Gets the session service.
	 * 
	 * @return the session service
	 */
	public static SessionService getService() {
		return service;
	}

	/**
	 * Sets the session service.
	 * 
	 * @param service
	 *            the session service to set
	 */
	public static void setService(SessionService service) {
		SettingsDAO.service = service;
	}

}
